package com.hzy.framework.biz.operationlog.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;

@Aspect
@Slf4j
public class ApioperationLogAspect {

    @Pointcut("@annotation(com.hzy.framework.biz.operationlog.aspect.ApiOperationLog)")
    public void apiOperationLog() {
    }

    @Around("apiOperationLog()")
    public Object doAroud(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        String className = joinPoint.getTarget().getClass().getSimpleName();
        String methodNname = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        String description = getApiOperationLogDescription(joinPoint);
        log.info("========请求开始:[{}],入参，{},请求类:{},请求方法:{}=======", description, args, className, methodNname);
        Object result = joinPoint.proceed();
        long execTime=System.currentTimeMillis()-startTime;
        log.info("=======请求结束:[{}],耗时:{}ms,出参:{}",description,execTime,result);
        return result;
    }


    private String getApiOperationLogDescription(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ApiOperationLog methodAnnotation = method.getAnnotation(ApiOperationLog.class);
        return methodAnnotation.description();
    }
}
